import { request } from '../../request/index'
import regeneratorRuntime from "../../lib/runtime/runtime"
Page({
  data: {
    leftMenuList: [],  // 左侧菜单数据
    rightContent: [],  // 右侧商品数据
    currentIndex: 0, // 被点击的菜单
    scrollTop: 0 // 右侧滚动条距顶部距离
  },
  cates: [],  // 接口的返回数据
  onLoad: function (options) {
    const Cates = wx.getStorageSync('cates')
    if(!Cates) {
      this.getCates();
    } else {
      if(Date.now() - Cates.time > 1000 * 300) { // 5min内有效 
        this.getCates();
      } else {
        this.cates = Cates.data;
        let leftMenuList = this.cates.map(v => v.cat_name);
        let rightContent = this.cates[0].children;
        this.setData({
          leftMenuList,
          rightContent
        })
      }
    }
  },
  // 获取分类数据
  async getCates() {
    const res = await request({ url: '/categories' });
    this.cates = res.data.message;
    wx.setStorageSync('cates', { time: Date.now(), data: this.cates })
    // 构造左侧菜单、右侧商品数据
    let leftMenuList = this.cates.map(v => v.cat_name);
    let rightContent = this.cates[0].children;
    this.setData({
      leftMenuList,
      rightContent
    })
  },
  // 左侧菜单的点击事件
  handItemTap(e) {
    const { index } = e.currentTarget.dataset;
    let rightContent = this.cates[index].children;
    this.setData({
      scrollTop: 0, // 重新设置scroll-view的距离
      rightContent,
      currentIndex: index
    })
  }
})